<template>
  <DistributorLayout>
    <div class="orders-page">
      <!-- 页面标题区域 -->
      <div class="page-header">
        <div class="header-left">
          <h1 class="page-title">订单管理</h1>
          <p class="page-subtitle">查看并管理通过您的代付链接生成的订单</p>
        </div>
        <div class="header-right">
          <button class="btn-export" @click="handleExportData">
            <i class="fas fa-file-export"></i> 导出数据
          </button>
        </div>
      </div>

      <!-- 订单统计区域 -->
      <div class="order-stats" v-if="!loading && orders.length > 0">
        <div class="stat-card">
          <div class="stat-value">{{ orderData.allNum }}</div>
          <div class="stat-label">全部佣金</div>
        </div>
        <div class="stat-card">
          <div class="stat-value">¥{{ orderData.yesNum }}</div>
          <div class="stat-label">已结算佣金</div>
        </div>
        <div class="stat-card highlight">
          <div class="stat-value">¥{{ orderData.noNum }}</div>
          <div class="stat-label">待结算佣金</div>
        </div>
      </div>

      <!-- 搜索和筛选区域 -->
      <!-- <div class="search-filter-section">
        <div class="search-box">
          <i class="fas fa-search search-icon"></i>
          <input type="text" class="search-input" placeholder="搜索订单编号或商品名称" v-model="searchQuery"
            @input="handleSearch" />
          <button class="clear-search" v-if="searchQuery" @click="clearSearch">
            <i class="fas fa-times"></i>
          </button>
        </div>

        <button class="toggle-filter-btn" @click="toggleFilterPanel">
          <i class="fas fa-filter"></i>
          {{ isFilterExpanded ? '收起筛选' : '高级筛选' }}
          <i class="fas" :class="isFilterExpanded ? 'fa-chevron-up' : 'fa-chevron-down'"></i>
        </button>
      </div> -->

      <!-- 订单表格 -->
      <OrdersTable @loadData="handleLoadData" />

      <!-- 页面为空时的提示 -->
      <div class="empty-state" v-if="!loading && !orders.length">
        <div class="empty-icon">
          <i class="fas fa-receipt"></i>
        </div>
        <h3 class="empty-title">暂无订单数据</h3>
        <p class="empty-description">
          您还没有任何订单，创建代付链接并分享给客户以接收订单
        </p>
        <router-link to="/distributor/payment-links" class="btn-create-link">
          <i class="fas fa-plus"></i> 创建代付链接
        </router-link>
      </div>

      <!-- 订单详情模态框 -->
      <OrderDetailModal v-model:visible="orderDetailVisible" :order-id="currentOrderId"
        @export="handleExportOrderDetail" />

      <!-- 操作成功提示 -->
      <transition name="fade">
        <div class="operation-message" v-if="operationMessage.show">
          <div class="message-content" :class="operationMessage.type">
            <i class="fas" :class="getMessageIcon()"></i>
            <span>{{ operationMessage.text }}</span>
          </div>
        </div>
      </transition>
    </div>
  </DistributorLayout>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, reactive } from 'vue'
import DistributorLayout from './DistributorLayout.vue'
import OrderFilter from '@/components/distributor/orders/OrderFilter.vue'
import OrdersTable from '@/components/distributor/orders/OrdersTable.vue'
import OrderDetailModal from '@/components/distributor/orders/OrderDetailModal.vue'
import { generateOrdersData } from '@/utils/mockData'

// 订单数据
const orders = ref<any[]>([])
const loading = ref(true)

// 筛选状态
const searchQuery = ref('')
const isFilterExpanded = ref(false)
const activeFilters = ref({
  dateRange: { start: '', end: '' },
  priceRange: [0, 1000] as [number, number],
  commissionRange: [null, null] as [number | null, number | null],
  categories: [] as string[],
  status: '' // 添加状态字段
})

// 操作提示信息
const operationMessage = ref({
  show: false,
  text: '',
  type: 'success' // success, error, warning, info
})

// 订单详情模态框
const orderDetailVisible = ref(false)
const currentOrderId = ref('')

// 获取订单数据
const fetchOrders = async () => {
  loading.value = true
  try {
    // 模拟API请求延迟
    await new Promise(resolve => setTimeout(resolve, 800))
    // 使用新添加的generateOrdersData函数生成订单数据
    orders.value = generateOrdersData(15)
  } catch (error) {
    console.error('获取订单数据失败:', error)
    showMessage('获取数据失败，请重试', 'error')
  } finally {
    loading.value = false
  }
}

// 处理搜索
const handleSearch = () => {
  // 这里可以添加防抖处理
}

// 清除搜索
const clearSearch = () => {
  searchQuery.value = ''
}

// 切换筛选面板
const toggleFilterPanel = () => {
  isFilterExpanded.value = !isFilterExpanded.value
}

// 处理筛选条件变化
const handleFilter = (filters: any) => {
  activeFilters.value = {
    ...filters,
    status: activeFilters.value.status // 保留状态筛选
  }
  // 在实际应用中，这里会根据筛选条件重新请求数据
  showMessage('筛选条件已应用', 'success')
}

// 处理重置筛选
const handleResetFilter = () => {
  // 重置筛选条件
  activeFilters.value = {
    dateRange: { start: '', end: '' },
    priceRange: [0, 1000],
    commissionRange: [null, null],
    categories: [],
    status: ''
  }
  showMessage('已重置筛选条件', 'info')
}

// 处理导出数据
const handleExportData = () => {
  showMessage('订单数据导出功能开发中', 'info')
}

// 格式化数字
const formatNumber = (num: number) => {
  return num.toFixed(2)
}

// 获取消息图标
const getMessageIcon = () => {
  switch (operationMessage.value.type) {
    case 'success': return 'fa-check-circle'
    case 'error': return 'fa-times-circle'
    case 'warning': return 'fa-exclamation-triangle'
    case 'info': return 'fa-info-circle'
    default: return 'fa-info-circle'
  }
}

// 显示操作提示消息
const showMessage = (text: string, type: 'success' | 'error' | 'warning' | 'info' = 'success') => {
  operationMessage.value = {
    show: true,
    text,
    type
  }

  // 自动隐藏消息
  setTimeout(() => {
    operationMessage.value.show = false
  }, 3000)
}

// 组件挂载时获取数据
onMounted(() => {
  fetchOrders()
})

// 订单统计数据
// const orderStats = computed(() => {
//   if (!orders.value.length) return { totalOrders: 0, totalAmount: 0, totalCommission: 0 }

//   const totalOrders = orders.value.length
//   const totalAmount = orders.value.reduce((sum, order) => sum + order.totalAmount, 0)
//   const totalCommission = orders.value.reduce((sum, order) => sum + order.commission, 0)

//   return {
//     totalOrders,
//     totalAmount,
//     totalCommission
//   }
// })

let orderData = reactive({
  allNum: '',
  yesNum: '',
  noNum: '',
})

const handleLoadData = (data: any = {}) => {
  console.log(11114, data);

  orderData.allNum = data.allNum || 0
  orderData.yesNum = data.yesNum || 0
  orderData.noNum = data.noNum || 0
}

// 处理表格组件的事件
const handleViewOrderDetails = (order: any) => {
  // 显示订单详情模态框
  currentOrderId.value = order.id
  orderDetailVisible.value = true
}

const handleTableStatusFilter = (status: string) => {
  // 由表格组件触发的状态筛选
  activeFilters.value.status = status === 'all' ? '' : status
}

const handleTableSort = (column: string, direction: 'asc' | 'desc') => {
  // 记录排序状态，实际排序在表格组件内部处理
  console.log(`排序: ${column} ${direction}`)
}

// 处理订单详情导出
const handleExportOrderDetail = (order: any) => {
  showMessage(`订单 ${order.orderNumber} 导出功能开发中`, 'info')
}
</script>

<style scoped lang="scss">
.orders-page {
  background: white;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

  // 页面标题区域
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;

    .header-left {
      .page-title {
        font-size: 24px;
        font-weight: 700;
        color: #2F3542;
        margin: 0 0 6px 0;
      }

      .page-subtitle {
        font-size: 14px;
        color: #6C757D;
        margin: 0;
      }
    }

    .header-right {
      .btn-export {
        display: inline-flex;
        align-items: center;
        justify-content: center;
        padding: 8px 16px;
        background-color: #F8F9FA;
        border: 1px solid #DFE3E8;
        color: #2F3542;
        border-radius: 6px;
        font-size: 14px;
        font-weight: 600;
        cursor: pointer;
        transition: all 0.2s ease;

        i {
          margin-right: 6px;
        }

        &:hover {
          background-color: #E9ECEF;
          transform: translateY(-2px);
          box-shadow: 0 3px 8px rgba(0, 0, 0, 0.1);
        }
      }
    }
  }

  // 订单统计区域
  .order-stats {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 16px;
    margin-bottom: 24px;

    .stat-card {
      background-color: #fff;
      border-radius: 8px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
      padding: 20px;
      text-align: center;
      transition: transform 0.2s;

      &:hover {
        transform: translateY(-3px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
      }

      .stat-value {
        font-size: 24px;
        font-weight: 700;
        color: #2F3542;
        margin-bottom: 8px;
      }

      .stat-label {
        font-size: 14px;
        color: #6C757D;
      }

      &.highlight {
        background-color: #FF4757;

        .stat-value {
          color: #fff;
        }

        .stat-label {
          color: rgba(255, 255, 255, 0.8);
        }
      }
    }

    @media (max-width: 768px) {
      grid-template-columns: 1fr;
    }
  }

  // 搜索和筛选区域
  .search-filter-section {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;

    .search-box {
      position: relative;
      flex: 1;
      max-width: 500px;

      .search-icon {
        position: absolute;
        left: 12px;
        top: 50%;
        transform: translateY(-50%);
        color: #ADB5BD;
      }

      .search-input {
        width: 100%;
        height: 42px;
        padding-left: 36px;
        padding-right: 36px;
        border: 1px solid #DFE3E8;
        border-radius: 6px;
        font-size: 14px;
        color: #2F3542;

        &:focus {
          outline: none;
          border-color: #FF4757;
          box-shadow: 0 0 0 2px rgba(255, 71, 87, 0.2);
        }

        &::placeholder {
          color: #ADB5BD;
        }
      }

      .clear-search {
        position: absolute;
        right: 12px;
        top: 50%;
        transform: translateY(-50%);
        background: none;
        border: none;
        color: #ADB5BD;
        cursor: pointer;
        padding: 4px;

        &:hover {
          color: #6C757D;
        }
      }
    }

    .toggle-filter-btn {
      display: inline-flex;
      align-items: center;
      padding: 8px 16px;
      margin-left: 16px;
      background-color: #F8F9FA;
      border: 1px solid #DFE3E8;
      border-radius: 6px;
      font-size: 14px;
      color: #2F3542;
      cursor: pointer;
      transition: all 0.2s ease;

      i:first-child {
        margin-right: 6px;
      }

      i:last-child {
        margin-left: 6px;
        font-size: 12px;
      }

      &:hover {
        background-color: #E9ECEF;
      }
    }
  }

  // 加载状态
  .placeholder-content {
    padding: 32px;
    display: flex;
    justify-content: center;
    align-items: center;
    margin: 40px 0;

    .loading-spinner {
      display: flex;
      flex-direction: column;
      align-items: center;
      color: #6C757D;

      i {
        font-size: 32px;
        margin-bottom: 16px;
        color: #FF4757;
      }
    }
  }

  // 空状态
  .empty-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 80px 20px;

    .empty-icon {
      font-size: 64px;
      color: #DFE3E8;
      margin-bottom: 24px;
    }

    .empty-title {
      font-size: 20px;
      font-weight: 600;
      color: #2F3542;
      margin: 0 0 12px 0;
    }

    .empty-description {
      font-size: 14px;
      color: #6C757D;
      margin: 0 0 24px 0;
      text-align: center;
      max-width: 400px;
    }

    .btn-create-link {
      display: inline-flex;
      align-items: center;
      justify-content: center;
      padding: 10px 20px;
      background-color: #FF4757;
      color: #fff;
      border: none;
      border-radius: 6px;
      font-size: 14px;
      font-weight: 600;
      cursor: pointer;
      transition: all 0.2s ease;
      text-decoration: none;

      i {
        margin-right: 8px;
      }

      &:hover {
        background-color: darken(#FF4757, 10%);
        transform: translateY(-2px);
        box-shadow: 0 3px 8px rgba(255, 71, 87, 0.3);
      }
    }
  }

  // 操作提示信息
  .operation-message {
    position: fixed;
    top: 20px;
    right: 20px;
    z-index: 1000;

    .message-content {
      display: flex;
      align-items: center;
      padding: 12px 16px;
      border-radius: 4px;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
      color: #fff;
      font-size: 14px;

      i {
        margin-right: 8px;
      }

      &.success {
        background-color: #28A745;
      }

      &.error {
        background-color: #DC3545;
      }

      &.warning {
        background-color: #FFC107;
        color: #212529;
      }

      &.info {
        background-color: #17A2B8;
      }
    }
  }

  // 淡入淡出动画
  .fade-enter-active,
  .fade-leave-active {
    transition: opacity 0.3s, transform 0.3s;
  }

  .fade-enter-from,
  .fade-leave-to {
    opacity: 0;
    transform: translateY(-20px);
  }
}

// 响应式样式
@media (max-width: 768px) {
  .orders-page {
    .page-header {
      flex-direction: column;
      align-items: flex-start;

      .header-left {
        margin-bottom: 16px;
      }

      .header-right {
        width: 100%;

        .btn-export {
          width: 100%;
        }
      }
    }

    .search-filter-section {
      flex-direction: column;

      .search-box {
        width: 100%;
        max-width: none;
        margin-bottom: 12px;
      }

      .toggle-filter-btn {
        width: 100%;
        margin-left: 0;
        justify-content: center;
      }
    }
  }
}
</style>
